import { SessionManager } from './session-manager.js';
import { ProxyManager } from '../utils/proxy.js';
import { StorageManager } from '../utils/storage.js';

class BackgroundService {
  constructor() {
    this.sessionManager = new SessionManager();
    this.proxyManager = new ProxyManager();
    this.storageManager = new StorageManager();
    this.isInitialized = false;
    this.init();
  }

  async init() {
    try {
      // 初始化会话管理器
      await this.sessionManager.init();
      
      // 监听扩展安装
      chrome.runtime.onInstalled.addListener(this.handleInstalled.bind(this));
      
      // 监听标签页更新
      chrome.tabs.onUpdated.addListener(this.handleTabUpdated.bind(this));
      
      // 监听标签页切换
      chrome.tabs.onActivated.addListener(this.handleTabActivated.bind(this));
      
      // 监听标签页关闭
      chrome.tabs.onRemoved.addListener(this.handleTabRemoved.bind(this));
      
      // 监听来自popup和content的消息
      chrome.runtime.onMessage.addListener(this.handleMessage.bind(this));
      
      // 监听右键菜单
      chrome.contextMenus.onClicked.addListener(this.handleContextMenu.bind(this));
      
      // 创建右键菜单
      this.createContextMenus();
      
      this.isInitialized = true;
      console.log('SessionBox: 后台服务初始化完成');
      
      // 设置定期 ping 来保持 Service Worker 活跃
      this.setupKeepAlive();
    } catch (error) {
      console.error('SessionBox: 后台服务初始化失败:', error);
    }
  }

  setupKeepAlive() {
    // 每 25 秒发送一次 ping 来保持 Service Worker 活跃
    setInterval(() => {
      console.log('Background: Service Worker 保持活跃 ping');
    }, 25000);
  }

  async handleInstalled(details) {
    if (details.reason === 'install') {
      try {
        // 首次安装，创建默认会话
        await this.sessionManager.createDefaultSession();
        console.log('SessionBox: 默认会话创建成功');
        
        // 打开欢迎页面
        chrome.tabs.create({
          url: chrome.runtime.getURL('options/options.html')
        });
      } catch (error) {
        console.error('SessionBox: 创建默认会话失败:', error);
      }
    } else if (details.reason === 'update') {
      console.log('SessionBox: 扩展已更新到版本', chrome.runtime.getManifest().version);
    }
  }

  async handleTabUpdated(tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete' && tab.url) {
      // 检查标签页是否属于某个会话
      const session = await this.sessionManager.getSessionByTabId(tabId);
      if (session) {
        // 应用会话配置
        await this.applySessionConfig(tabId, session);
      }
    }
  }

  async handleTabActivated(activeInfo) {
    const session = await this.sessionManager.getSessionByTabId(activeInfo.tabId);
    if (session) {
      // 更新当前活动会话
      await this.sessionManager.setActiveSession(session.id);
    }
  }

  async handleTabRemoved(tabId, removeInfo) {
    // 清理会话标签页记录
    await this.sessionManager.removeTabFromSession(tabId);
  }

  handleMessage(request, sender, sendResponse) {
    console.log('Background: 收到消息:', request.action);
    
    // 使用异步函数处理消息，但立即返回 true 保持端口开放
    (async () => {
      try {
        // 检查是否已初始化
        if (!this.isInitialized) {
          console.log('Background: 扩展未初始化');
          sendResponse({ success: false, error: '扩展正在初始化中，请稍后重试' });
          return;
        }

        switch (request.action) {
          case 'createSession':
            console.log('Background: 收到创建会话请求，配置:', request.config);
            const newSession = await this.sessionManager.createSession(request.config);
            console.log('Background: 会话创建成功:', newSession);
            sendResponse({ success: true, session: newSession });
            break;

          case 'createSessionFromCurrentPage':
            console.log('Background: 收到从当前页面创建会话请求，配置:', request.config);
            
            // 如果 sender.tab 不存在（如从弹窗发送），获取当前活动标签页
            let currentTabId = sender.tab?.id;
            if (!currentTabId) {
              const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
              if (tabs.length > 0) {
                currentTabId = tabs[0].id;
                console.log('Background: 从弹窗发送，使用当前活动标签页:', currentTabId);
              } else {
                throw new Error('无法获取当前标签页信息');
              }
            }
            
            const result = await this.sessionManager.createSessionFromCurrentPage(currentTabId, request.config);
            console.log('Background: 从当前页面创建会话成功:', result);
            sendResponse({ success: true, session: result.session, tab: result.tab });
            break;
            
          case 'deleteSession':
            await this.sessionManager.deleteSession(request.sessionId);
            sendResponse({ success: true });
            break;

          case 'setSessionCookie':
            console.log('Background: 设置会话Cookie，会话ID:', request.sessionId);
            await this.sessionManager.setSessionCookie(request.sessionId, request.cookie);
            sendResponse({ success: true });
            break;
            
          case 'switchSession':
            // 如果 sender.tab 不存在，获取当前活动标签页
            let tabIdForSwitch = sender.tab?.id;
            if (!tabIdForSwitch) {
              const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
              if (tabs.length > 0) {
                tabIdForSwitch = tabs[0].id;
              }
            }
            
            await this.sessionManager.switchToSession(request.sessionId, tabIdForSwitch);
            sendResponse({ success: true });
            break;
            
          case 'getSessions':
            const sessions = await this.sessionManager.getAllSessions();
            sendResponse({ success: true, sessions });
            break;
            
          case 'updateSession':
            await this.sessionManager.updateSession(request.sessionId, request.config);
            sendResponse({ success: true });
            break;
            
          case 'openInSession':
            const tab = await this.sessionManager.openUrlInSession(request.url, request.sessionId);
            sendResponse({ success: true, tab });
            break;
            
          case 'getCurrentSession':
            let currentSession = null;
            let tabIdForCurrent = sender.tab?.id;
            
            if (!tabIdForCurrent) {
              const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
              if (tabs.length > 0) {
                tabIdForCurrent = tabs[0].id;
              }
            }
            
            if (tabIdForCurrent) {
              currentSession = await this.sessionManager.getSessionByTabId(tabIdForCurrent);
            }
            
            sendResponse({ success: true, session: currentSession });
            break;
            
          case 'getSessionFingerprint':
            let sessionForFingerprint = null;
            let tabIdForFingerprint = sender.tab?.id;
            
            if (!tabIdForFingerprint) {
              const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
              if (tabs.length > 0) {
                tabIdForFingerprint = tabs[0].id;
              }
            }
            
            if (tabIdForFingerprint) {
              sessionForFingerprint = await this.sessionManager.getSessionByTabId(tabIdForFingerprint);
            }
            
            sendResponse({ 
              success: true, 
              config: sessionForFingerprint ? sessionForFingerprint.fingerprintConfig || {} : {}
            });
            break;
            
          case 'saveSessionStorage':
            console.log('Background: 保存会话存储，会话ID:', request.sessionId, '类型:', request.type);
            await this.sessionManager.saveSessionStorage(request.sessionId, request.type, request.data);
            sendResponse({ success: true });
            break;
            
          case 'getSessionStorage':
            console.log('Background: 获取会话存储，会话ID:', request.sessionId);
            const storageData = await this.sessionManager.getSessionStorage(request.sessionId);
            sendResponse({ success: true, data: storageData });
            break;
            
          case 'saveSessionCookies':
            console.log('Background: 保存会话Cookie，会话ID:', request.sessionId);
            await this.sessionManager.saveSessionCookies(request.sessionId, request.cookies);
            sendResponse({ success: true });
            break;
            
          case 'getSessionCookies':
            console.log('Background: 获取会话Cookie，会话ID:', request.sessionId);
            const cookieData = await this.sessionManager.getSessionCookies(request.sessionId);
            sendResponse({ success: true, cookies: cookieData });
            break;

          case 'ping':
            sendResponse({ success: true, message: 'pong' });
            break;
            
          default:
            console.log('Background: 未知操作:', request.action);
            sendResponse({ success: false, error: '未知操作' });
        }
      } catch (error) {
        console.error('Background: 消息处理错误:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    
    return true; // 保持消息通道开放
  }

  createContextMenus() {
    chrome.contextMenus.create({
      id: 'openInNewSession',
      title: '在新会话中打开',
      contexts: ['link']
    });
    
    chrome.contextMenus.create({
      id: 'sessionSeparator',
      type: 'separator',
      contexts: ['link']
    });
  }

  async handleContextMenu(info, tab) {
    if (info.menuItemId === 'openInNewSession') {
      // 在新会话中打开链接
      const session = await this.sessionManager.createQuickSession();
      await this.sessionManager.openUrlInSession(info.linkUrl, session.id);
    }
  }

  async applySessionConfig(tabId, session) {
    // 应用代理设置
    if (session.proxy && session.proxy.enabled) {
      await this.proxyManager.setProxyForTab(tabId, session.proxy);
    }
    
    // 注入指纹保护脚本
    if (session.fingerprintProtection) {
      await chrome.scripting.executeScript({
        target: { tabId },
        files: ['utils/fingerprint.js']
      });
    }
  }
}

// 初始化后台服务
new BackgroundService(); 